<template>
    <div id="home">
        <el-container>
            <!-- 左侧：标记记录 -->
            <el-aside width="25%">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span>标记选框的记录信息</span>
                    </div>
                    <ul>
                        <li v-for="(mark, index) in marks" :key="index">
                            <div>
                                <span>
                                    {{ `标记 ${index + 1}: X=${mark.startX}, Y=${mark.startY},
                                    宽=${mark.width},高=${mark.height}` }}
                                    {{ mark.isHasRangeTime ? `,开始时间：${mark.startTime},结束时间：${mark.endTime}` : '' }}
                                </span>
                            </div>
                            <el-button type="danger" @click="deleteMark(index)" size="mini"
                                style="margin-left: 10px;">删除</el-button>
                            <el-button v-if="mark.isHasRangeTime == false" @click="addStartTime(index)" size="mini"
                                style="margin-left: 10px;">开始</el-button>
                            <el-button v-if="mark.isHasRangeTime && mark.startTime !== '' && mark.endTime === ''"
                                @click="addEndTime(index)" size="mini" style="margin-left: 10px;">结束</el-button>
                        </li>
                    </ul>
                </el-card>
            </el-aside>
            <!-- 中间：视频显示 -->
            <el-aside width="50%">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span>视频水印操作区域</span>
                    </div>
                    <div>
                        <div style="display: flex; justify-content: space-between;">
                            <el-button type="success" @click="selectVideo">选择视频</el-button>
                            <el-button type="primary" @click="removeWatermark">去水印</el-button>
                        </div>

                        <div style="position: relative;" class="video-container">
                            <video class="video-player-box" ref="videoPlayer" :src="videoSrc" @dblclick.prevent
                                @keydown.f.prevent @mousedown="startMark" @mousemove="drawTempRect"
                                @mouseup="endMark"></video>
                            <canvas ref="canvas" class="canvas-overlay"></canvas>
                        </div>

                        <!-- 自定义控制条 -->
                        <div class="custom-controls">
                            <el-button @click="togglePlay" type="text" icon="el-icon-video-play"
                                v-if="!isPlaying"></el-button>
                            <el-button @click="togglePlay" type="text" icon="el-icon-video-pause" v-else></el-button>
                            <el-slider v-model="progress" :step="0.0001" :max="100" @change="seekVideo"
                                style="flex: 1; margin: 0 10px;"></el-slider>
                            <span>{{ currentTimeFormatted }}</span> <!-- 当前时间 -->
                            <span>/</span>
                            <span>{{ totalTimeFormatted }}</span> <!-- 总时间 -->
                        </div>
                    </div>
                </el-card>
            </el-aside>
            <!-- 右侧：配置空间 -->
            <el-aside width="25%">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span>配置空间</span>
                    </div>
                    <div>
                        <el-form ref="form" label-width="80px">
                            <el-form-item label="GPU加速">
                                <el-switch v-model="canGpu"></el-switch>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-card>
            </el-aside>
        </el-container>
    </div>
</template>

<script>

const { ipcRenderer } = require('electron');

import fs from 'fs';
export default {
    name: "home-page",
    data() {
        return {
            videoSrc: "",
            marks: [], // 存储所有标记
            currentMark: null,
            startPoint: null,
            endPoint: null,
            videoWidth: 0,
            videoHeight: 0,
            canvas: null,
            ctx: null,
            isDrawing: false, // 是否正在绘制选框
            filePath: "",
            canGpu: false,
            progress: 0, // 进度条百分比
            isPlaying: false,
            videoDuration: 0,
            currentTime: 0, // 当前播放时间
            totalTime: 0, // 视频总时长
        };
    },
    mounted() {
        const video = this.$refs.videoPlayer;
        // 禁用双击全屏
        video.addEventListener("dblclick", (event) => {
            event.preventDefault();
        });
        // 禁用单击全屏
        video.addEventListener("click", (event) => {
            event.preventDefault();
        });
        // 禁用键盘快捷键（如 F 键）
        document.addEventListener("keydown", (event) => {
            if (event.key === "f" || event.code === "KeyF") {
                event.preventDefault();
            }
        });

        // 监听视频的时间更新事件
        video.addEventListener("timeupdate", () => {
            this.updateProgress();
            this.currentTime = video.currentTime;
        });

        // 监听视频的元数据加载完成事件
        video.addEventListener("loadedmetadata", () => {
            this.totalTime = video.duration;
        });
    },
    computed: {
        // 格式化当前时间
        currentTimeFormatted() {
            return this.formatTime(this.currentTime);
        },
        // 格式化总时间
        totalTimeFormatted() {
            return this.formatTime(this.totalTime);
        },
    },

    methods: {

        // 时间格式化工具函数
        formatTime(seconds) {
            const hours = Math.floor(seconds / 3600); // 计算小时
            const minutes = Math.floor((seconds % 3600) / 60); // 计算分钟
            const remainingSeconds = Math.floor(seconds % 60); // 计算秒
            // 格式化为 时:分:秒
            return `${hours}:${minutes < 10 ? '0' : ''}${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
        },
        updateProgress() {
            const video = this.$refs.videoPlayer;
            this.progress = (video.currentTime / video.duration) * 100;
        },
        // 用户释放滑块后触发（实际跳转到指定时间点）
        seekVideo(value) {
            const video = this.$refs.videoPlayer;
            console.log('Seek to:', value);
            // 跳转到指定时间点
            video.currentTime = (value / 100) * video.duration;
        },
        async selectVideo() {
            try {
                // 调用主进程打开文件选择对话框
                const filePath = await ipcRenderer.invoke('open-file-dialog');
                if (filePath) {
                    this.filePath = filePath;
                    // 将文件路径转换为 Blob URL（可选）
                    const fileBuffer = fs.readFileSync(this.filePath);
                    const blob = new Blob([fileBuffer], { type: 'video/mp4' });
                    this.videoSrc = URL.createObjectURL(blob);
                    console.log('Video source:', this.videoSrc);
                    this.marks = []; // 清空之前的标记
                    this.$nextTick(() => {
                        const video = this.$refs.videoPlayer;
                        video.addEventListener("loadedmetadata", () => {
                            this.videoWidth = video.videoWidth;
                            this.videoHeight = video.videoHeight;
                            this.canvas.width = this.videoWidth;
                            this.canvas.height = this.videoHeight;
                            // 计算缩放比例
                            this.scaleX = this.videoWidth / video.clientWidth;
                            this.scaleY = this.videoHeight / video.clientHeight;
                        });
                        this.canvas = this.$refs.canvas;
                        this.ctx = this.canvas.getContext("2d");
                    });
                } else {
                    console.log('用户取消了文件选择');
                }
            } catch (error) {
                console.error('Error selecting video:', error);
            }
        },

        deleteMark(index) {
            // Remove the selected mark from the marks array
            this.marks.splice(index, 1);

            // Redraw the remaining marks on the canvas
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
            this.drawAllMarks();
        },

        addStartTime(index) {
            // Remove the selected mark from the marks array
            this.marks[index].startTime = Math.floor(this.currentTime);
            this.marks[index].isHasRangeTime = true;
        },
        addEndTime(index) {
            this.marks[index].endTime = Math.floor(this.currentTime);
        },
        startMark(event) {
            const video = this.$refs.videoPlayer;
            const rect = video.getBoundingClientRect();
            this.startPoint = {
                x: (event.clientX - rect.left) * this.scaleX, // 映射到实际分辨率
                y: (event.clientY - rect.top) * this.scaleY,
            };
            this.isDrawing = true;
        },
        drawTempRect(event) {
            if (!this.isDrawing) return;
            const video = this.$refs.videoPlayer;
            const rect = video.getBoundingClientRect();
            this.endPoint = {
                x: (event.clientX - rect.left) * this.scaleX, // 映射到实际分辨率
                y: (event.clientY - rect.top) * this.scaleY,
            };
            // 清除画布
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
            // 绘制临时选框
            const startX = Math.min(this.startPoint.x, this.endPoint.x);
            const startY = Math.min(this.startPoint.y, this.endPoint.y);
            const width = Math.abs(this.endPoint.x - this.startPoint.x);
            const height = Math.abs(this.endPoint.y - this.startPoint.y);
            this.ctx.strokeStyle = "red";
            this.ctx.lineWidth = 2;
            this.ctx.strokeRect(startX, startY, width, height);
        },
        endMark() {
            if (!this.isDrawing) return;
            const startX = Math.round(Math.min(this.startPoint.x, this.endPoint.x));
            const startY = Math.round(Math.min(this.startPoint.y, this.endPoint.y));
            const width = Math.round(Math.abs(this.endPoint.x - this.startPoint.x));
            const height = Math.round(Math.abs(this.endPoint.y - this.startPoint.y));
            // 保存标记
            this.marks.push({
                startX,
                startY,
                width,
                height,
                startTime: "",
                endTime: "",
                isHasRangeTime: false,
            });
            // 清除画布并重新绘制所有标记
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
            this.drawAllMarks();
            this.isDrawing = false;
        },
        drawAllMarks() {
            this.ctx.strokeStyle = "red";
            this.ctx.lineWidth = 2;
            this.marks.forEach((mark) => {
                this.ctx.strokeRect(mark.startX, mark.startY, mark.width, mark.height);
            });
        },
        async removeWatermark() {
            if (this.marks.length === 0) {
                this.$message.error('请先选择去水印区域');
                return;
            }
            const videoPath = this.filePath;
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });

            // 监听 ffmpeg 进度
            ipcRenderer.on('ffmpeg-progress', (event, percent) => {
                loading.text = `处理中... ${Math.round(percent)}%`;
            });

            // 调用主进程打开文件选择对话框
            const filePath = await ipcRenderer.invoke('remove-watermark', videoPath, this.marks, this.canGpu);
            if (filePath) {
                this.$message.success('消除水印成功');
                loading.close();
                const fileDirectory = await ipcRenderer.invoke('select-directory');
                if (fileDirectory) {
                    //在这个将处理好的filePath保存到fileDirectory中
                    await ipcRenderer.invoke('save-video', filePath, fileDirectory);
                    this.$message.success('已将视频保存到目录上了');
                } else {
                    this.$message.error('未选择保存目录');
                }
                // 删除原始处理好的文件
                await ipcRenderer.invoke('delete-file', filePath);
            } else {
                this.$message.error('消除水印失败');
            }
        },

        togglePlay() {
            const video = this.$refs.videoPlayer;
            if (video.paused) {
                video.play();
                this.isPlaying = true;
            } else {
                video.pause();
                this.isPlaying = false;
            }
        },

        updateProgress() {
            const video = this.$refs.videoPlayer;
            this.progress = (video.currentTime / video.duration) * 100;
        },
    },
};
</script>
<style scoped lang="less">
.video-player-box {
    width: 100%;
    height: auto;
    position: relative;
    /* 确保视频组件是相对定位的 */
}

.canvas-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    /* 防止画布影响视频的交互 */
}

/* 隐藏全屏按钮 */
video::-webkit-media-controls-fullscreen-button {
    display: none;
}

/* 添加带有质感的边框 */
.video-container {
    border: 2px solid #ccc;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    overflow: hidden;
    background-color: #f9f9f9;
}

.custom-controls {
    display: flex;
    align-items: center;
    /* 垂直居中 */
    justify-content: space-between;
    /* 内容均匀分布 */
    margin-top: 10px;
}

.custom-controls .el-slider {
    flex: 1;
    /* 让进度条占据剩余空间 */
    margin: 0 10px;
    /* 左右间距 */
}

.custom-controls span {
    font-size: 14px;
    color: #666;
}
</style>